#!/bin/bash

#=======================================================================
# mkFiles
# File ID: 571d0be4-08ef-11de-8399-000475e441b9
# Creates Files.json in current directory.
#=======================================================================

# FIXME: Why doesn’t the ^ (caret) work with "grep -z" ?

test -w /tmp/. || { echo mkFiles: /tmp/: Directory not writable or not found >&2; exit 1; };
lockname=mkFiles.lock
until mkdir $lockname 2>/dev/null; do
	echo $0: $lockname: Waiting for lock... >&2
	sleep 5
done

unset suuid_m
if test "$1" = "-m"; then
    shift
    suuid_m=" -m"
fi

tmpjson=/tmp/.mkFiles.$uuid.tmp
find -type f -print0 | \
    grep -zv '/\.git/' | \
    LC_COLLATE=C sort -z | \
    fldb -z -f - >>$tmpjson
mv $tmpjson Files.json
fileinfo="$(fldb Files.json | json_reformat -m)"
uuid=`suuid$suuid_m -t mkfiles --raw -w eo -c "<c_mkfiles> <host>$(hostname)</host> <directory>$(/bin/pwd)</directory> <fileinfo>$fileinfo</fileinfo> </c_mkfiles>"` || { echo mkFiles: suuid error >&2; rmdir $lockname; exit 1; }
echo mkFiles: Done.

rmdir $lockname
